const express = require('express')
let mongoose = require('mongoose')
const app = express()
const db = require('./db/you')
const { urea1Rule, customRule, userRule, memberRule, sanhuRule, cardsManageRule, chaiyouRule, niaosuRule, cardsRule, sanhuDataRule, ChaiyouDataRule, ChaiyouShouyiRule } = require('./model/userModel')
const bodyParser = require('body-parser')
const jwt = require('jsonwebtoken')
const { forEach } = require('lodash')
const { resolve } = require('path')
app.disable('x-powered-by')
    // import bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
db(() => {
    app.get('/', function(req, res) {
        res.send('ok')
    })
    app.listen(3000, (err) => {
            if (!err) console.log('服务器启动成功')
            else console.log(err)
        })
        //数据库连接
    let urea1 = mongoose.model('urea1', urea1Rule)
    let custom = mongoose.model('customs', customRule)
    let user = mongoose.model('users', userRule)
    let member = mongoose.model('members', memberRule)
    let sanhu = mongoose.model('sanhus', sanhuRule)
    let chaiyou = mongoose.model('chaiyous', chaiyouRule)
    let cardsMan = mongoose.model('cardsmanages', cardsManageRule)
    let niaosu = mongoose.model('niaosus', niaosuRule)
    let sanhuData = mongoose.model('sanhudatas', sanhuDataRule)
    let cardm = mongoose.model('cardm', cardsRule)
    let chaiyouData = mongoose.model('chaiyoudatas', ChaiyouDataRule)
    let chaiyouShouyi = mongoose.model('chaiyoushouyis', ChaiyouShouyiRule)
    let dataObj = {}
        ///查询所有库中存在的柴油名称，然后根据尿素名称查询对应的数据
    app.get('/findChaiyouName', (req, res) => {
        chaiyou.find({ display: 'YES' }).then(datas => {
            res.send(datas)
        })
    });
    /////////添加柴油数据
    app.post('/addChaiyouData', (req, res) => {
        const { name, datas, date, stringDate } = req.body
        chaiyouData.create({

            createTime: new Date(),
            name,
            datas,
            date,
            stringDate
        }, function(err, data) {
            if (!err) {
                console.log('油卡信息添加成功')
                res.send('油卡信息油添加成功')
            } else {
                console.log(err + '油卡信息添加失败')
            }
        })
    });
    ///////////////////新加油枪(柴油)当前销量数据
    app.post('/addChaiyouShouyi', (req, res) => {
        const { name, datas, date, stringDate } = req.body
        let das
        chaiyouData.find({ date: { $lt: date }, name }).sort({ _id: -1 }).limit(1).then(data => {

                if (data.length > 0) {
                    dataObj = data[data.length - 1]
                    das = (Number(datas) - dataObj.datas)
                } else {
                    das = datas
                }

            }).then((resole, reject) => {
                chaiyouShouyi.create({
                    datas: das,
                    date,
                    stringDate,
                    createTime: new Date(),
                    name
                }, function(err) {
                    if (!err) {
                        console.log('油表每天销售情况添加成功')
                        res.send('油表每天销售情况添加成功')
                    } else {
                        console.log(err)
                    }
                })
            })
            .catch(err => {

            });
    });
    ///////////////////查询油枪(柴油)当前销量数据
    app.get('/findShouyiData', (req, res) => {
        chaiyou.find({ display: "YES" }).then(datas => {
            chaiyouShouyi.aggregate([{ $group: { _id: "$date", dates: { $max: '$stringDate' } } }]).sort({ _id: -1 }).then(data => {
                //按日期分类，一共有多少个日期
                chaiyouShouyi.find({}).sort({ _id: -1 }).then(datam => {
                    //所有数据，在这里面根据日期，名称重新写入数据                   
                    let das = []
                    let names = {}
                    for (let i = 0; i < data.length; i++) {
                        let items = {}
                        let dd = 0
                        for (let j = 0; j < datas.length; j++) {
                            items.date = data[i]._id
                            items.stringDate = data[i].dates
                            names["data" + j] = datas[j].name
                            items['data' + j] = 0
                            for (let k = 0; k < datam.length; k++) {
                                if ((datam[k].stringDate === data[i].dates) && (datam[k].name === datas[j].name)) {
                                    items['data' + j] = datam[k].datas
                                    dd += datam[k].datas
                                    items['total'] = dd
                                }
                            }
                        }
                        das.push(items)
                    }
                    das.push(names)
                    console.log('柴油收益数据查询成功')
                    res.send(das)
                }).catch(err => {
                    console.log(err + '柴油收益数据查询失败')
                })
            })
        })
    });
    //前后联动后 //柴油数据查询
    app.get('/findChaiyouData', (req, res) => {

        chaiyou.find({ display: "YES" }).then(datas => {
            // cardm.find({}).sort({ date: -1 })
            //所有的油卡类型
            chaiyouData.aggregate([{ $group: { _id: "$date", dates: { $max: '$stringDate' } } }]).sort({ _id: -1 }).then(data => {
                //按日期分类，一共有多少个日期
                chaiyouData.find({}).sort({ _id: -1 }).then(datam => {
                    //所有数据，在这里面根据日期，名称重新写入数据
                    let das = []
                    let names = {}
                    for (let i = 0; i < data.length; i++) {
                        let items = {}
                        for (let j = 0; j < datas.length; j++) {
                            items.date = data[i]._id
                            items.stringDate = data[i].dates
                            names["data" + j] = datas[j].name
                            items['data' + j] = 0
                            for (let k = 0; k < datam.length; k++) {
                                if ((datam[k].stringDate === data[i].dates) && (datam[k].name === datas[j].name)) {
                                    items['data' + j] = datam[k].datas
                                }
                            }
                        }
                        das.push(items)
                    }
                    das.push(names)
                    console.log('油卡数据查询成功')
                    res.send(das)
                }).catch(err => {
                    console.log(err + '油卡数据查询失败')
                })
            })
        })
    });
    ///////////////编辑柴油数据
    app.post('/editChaiyouData', (req, res) => {
        const { stringDate, name, datas, date } = req.body
        chaiyouData.updateOne({ stringDate, name }, {
            $set: {
                datas
            }
        }, function(err, dta) {
            if (!err) {
                console.log('编辑某天油枪销量成功')
                chaiyouData.find({ date: { $lt: date }, name }).sort({ date: -1 }).limit(1).then(datas11 => {
                    //如果当前数据不是最后一条数据，则执行下面语句，将改变数据直接赋值到当天销量中
                    if (datas11.length > 0) {
                        let o1
                        o1 = Number(datas) - datas11[0].datas
                            //用当前数据，减去它的前一天的数据，则是当前（当天）的销量
                        chaiyouShouyi.updateOne({ date: date, name }, {
                            $set: {
                                datas: o1
                            }
                        }).then(d5 => {
                            //用当前数据第二天数据减去当前的数据，则是当前的第二天（后一天）的销量
                            chaiyouData.find({ date: { $gt: date }, name }).limit(1).then(d9 => {
                                //如果当前数据没有后一天数据，返回，否则执行改变
                                if (d9.length === 0) return
                                chaiyouShouyi.updateOne({ date: d9[0].date, name }, {
                                    $set: {
                                        datas: (d9[0].datas - Number(datas))
                                    }
                                }).then(ii => {

                                })
                            })
                        });
                        //如果当前数据是最后一条数据，将改变数据直接赋值到当天销量中
                    } else {
                        chaiyouShouyi.updateOne({ date: date, name }, {
                            $set: {
                                datas
                            }
                        }).then(resolve => {
                            //如果当前数据是最后一条数据，将用当前的后面一（第二）天的数据减去当前的数据，变是当前的后面一（第二天）的销量
                            chaiyouData.find({ date: { $gt: date }, name }).limit(1).then(d8 => {
                                //如果当前数据没有后一天数据，返回，否则执行改变
                                if (d8.length === 0) return
                                chaiyouShouyi.updateOne({ date: d8[0].date }, {
                                    $set: {
                                        datas: (d8[0].datas - Number(datas))
                                    }
                                }).then(ii => {})
                            })
                        });
                    }
                })
                res.send('编辑某天油枪销量成功')
            } else {
                console.log(err + '编辑某天油枪销量失败')
            }
        })

    });
    //查找所有库中存在的尿素名称，然后根据尿素名称查询对应的数据
    app.get('/findUreaName', (req, res) => {
        niaosu.find({ display: 'YES' }).then(datas => {
            res.send(datas)
        })
    });
    //所有尿素进出货情况查询，用来导出excel
    app.get('/urea1All', (req, res) => {
        urea1.find({}).sort({ _id: -1 }).then(datas => {
            console.log('第一号油的数据查询成功')
            res.send(datas)
        }).catch(err => {
            console.log(err + '第一号油的数据查询失败')
        })
    });
    //按不同型号的数据查询
    app.get('/urea1', (req, res) => {
        const { name } = req.query
        urea1.find({ name }).sort({ _id: -1 }).then(datas => {
            // urea1.find({}).sort({ _id: -1 }).then(datas => {
            console.log('第一号油的数据查询成功')
            res.send(datas)
        }).catch(err => {
            console.log(err + '第一号油的数据查询失败')
        })
    });
    //第一号油的数据添加，进货，出货情况
    app.post('/addUrea1', (req, res) => {
        const { enter, out, date, stringDate, name } = req.body
        let totals = 0
        let leftover = (Number(enter) - Number(out))
        urea1.find({ name }).sort({ _id: -1 }).limit(1).then(data => {
            if (data.length == 0) {
                totals = leftover
            } else {
                totals = (data[0].totals + leftover)
            }
        }).then((resolve, reject) => {
            urea1.create({
                name,
                enter,
                out,
                leftover: leftover,
                date: date,
                createTime: new Date(),
                totals: totals,
                stringDate
            }, function(err, data) {
                if (!err) {
                    console.log('第一号油添加成功')
                    res.send('第一号油添加成功')
                } else {
                    console.log(err + '第一号油添加失败')
                }
            })
        })
    });
    //编辑时先查询某一条数据，返回页面
    app.post('/findOneUrea1', (req, res) => {
        const { _id } = req.body
        urea1.findOne({ _id: _id }, function(err, data) {
            if (!err) {
                res.send(data)
                console.log('想要编辑的一号油数据查询成功')
            } else {
                console.log(err + '想要编辑的一号油数据查询失败')
            }
        })
    });
    //执行编辑某一条数据
    app.post('/editUrea1', (req, res) => {
        const {
            enter,
            out,
            _id,
            date,
            name
        } = req.body
        let leftover = (Number(enter) - Number(out))
        urea1.updateOne({ _id: _id }, {
            $set: {
                enter,
                out,
                leftover: leftover
            }
        }, function(err, data) {
            if (!err) {
                console.log('执行编辑一号油数据成功')
                urea1.find({ date: { $lt: date }, name }).sort({ _id: -1 }).limit(1).then(data => {

                    let ts
                    if (data.length > 0) {
                        ts = (data[0].totals + leftover)
                        urea1.updateOne({ _id }, {
                            $set: {
                                totals: ts
                            }
                        }, function() {
                            urea1.find({ date: { $gt: date }, name }).then(datas => {

                                let tts = ts
                                for (let j = 0; j < datas.length; j++) {
                                    tts = (tts + datas[j].leftover)

                                    urea1.updateOne({ _id: datas[j]._id }, {
                                        $set: {
                                            totals: tts
                                        }
                                    }, function() {

                                    })
                                }
                            });
                        })
                    } else {
                        ts = leftover
                        urea1.updateOne({ _id }, {
                            $set: {
                                totals: ts
                            }
                        }, function() {
                            urea1.find({ date: { $gt: date }, name }).then(datas => {
                                let tts = ts
                                for (let j = 0; j < datas.length; j++) {
                                    tts = (tts + datas[j].leftover)
                                    urea1.updateOne({ _id: datas[j]._id }, {
                                        $set: {
                                            totals: tts
                                        }
                                    }, function() {})
                                }
                            });
                        })
                    }
                });
                res.send('执行编辑一号油数据成功')
            } else {
                console.log(err + '执行编辑一号油数据失败')
            }
        })
    });
    ///添加散户数据
    app.post('/addSanhuData', (req, res) => {
        const { name, datas, date, stringDate, totals } = req.body
        sanhuData.create({
            createTime: new Date(),
            name,
            datas,
            date,
            stringDate,
            totals
        }, function(err, data) {
            if (!err) {
                console.log('油卡信息添加成功')
                res.send('油卡信息油添加成功')
            } else {
                console.log(err + '油卡信息添加失败')
            }
        })
    });
    ///查询所有散户类型
    app.get('/addSanhuName', (req, res) => {
        sanhu.find({ display: 'YES' }).then(datas => {
            res.send(datas)
        })
    });
    ///////////////////查询散户数据
    app.get('/findSanhuData', (req, res) => {
        sanhu.find({ display: "YES" }).then(datas => {
            //所有的散户类型
            sanhuData.aggregate([{ $group: { _id: "$date", dates: { $max: '$stringDate' } } }]).sort({ _id: -1 }).then(data => {
                //按日期分类，一共有多少个日期
                sanhuData.find({}).sort({ _id: -1 }).then(datam => {
                    //所有数据，在这里面根据日期，名称重新写入数据                    
                    let das = []
                    let names = {}
                    for (let i = 0; i < data.length; i++) {
                        let items = {}
                        for (let j = 0; j < datas.length; j++) {
                            items.date = data[i]._id
                            items.stringDate = data[i].dates
                            names["data" + j] = datas[j].name
                            let dd = 0
                            items['data' + j] = 0
                            for (let k = 0; k < datam.length; k++) {
                                if ((datam[k].stringDate === data[i].dates) && (datam[k].name === datas[j].name)) {
                                    items['data' + j] = datam[k].datas
                                    dd = datam[k].totals
                                    items['total'] = dd
                                }
                            }
                        }
                        das.push(items)
                    }
                    das.push(names)
                    console.log('散户数据查询成功')
                    res.send(das)
                }).catch(err => {
                    console.log(err + '散户数据查询失败')
                })
            })
        })
    });
    ///////////////编辑散户数据
    app.post('/editSanhu', (req, res) => {
        const { stringDate, name, datas, totals, date } = req.body
        sanhuData.updateOne({ stringDate, name }, {
            $set: {
                datas,
                totals
            }
        }).then(data => {
            if (data.n === 0) {
                sanhuData.create({
                    createTime: new Date(),
                    name,
                    datas,
                    date,
                    stringDate,
                    totals
                })
            }
            res.send('ok')
        })
    });
    //查找所有库中存在的油卡名称，然后根据油卡名称查询对应的数据
    app.get('/findCardName', (req, res) => {
        cardsMan.find({ display: 'YES' }).then(datas => {
            res.send(datas)
        })
    });
    //////////////////添加油卡信息
    app.post('/addCards', (req, res) => {
        const { name, datas, date, stringDate, totals } = req.body
        cardm.create({
            createTime: new Date(),
            name,
            datas,
            date,
            stringDate,
            totals
        }, function(err, data) {
            if (!err) {
                console.log('油卡信息添加成功')
                res.send('油卡信息油添加成功')
            } else {
                console.log(err + '油卡信息添加失败')
            }
        })
    });
    //前后联动后 //油卡数据查询
    app.get('/findCardm', (req, res) => {
        cardsMan.find({ display: "YES" }).then(datas => {
            // cardm.find({}).sort({ date: -1 })
            //所有的油卡类型
            cardm.aggregate([{ $group: { _id: "$date", dates: { $max: '$stringDate' } } }]).sort({ _id: -1 }).then(data => {
                //按日期分类，一共有多少个日期
                cardm.find({}).sort({ _id: -1 }).then(datam => {
                    //所有数据，在这里面根据日期，名称重新写入数据
                    let das = []
                    let names = {}
                    for (let i = 0; i < data.length; i++) {
                        let items = {}
                        for (let j = 0; j < datas.length; j++) {
                            items.date = data[i]._id
                            items.stringDate = data[i].dates
                            names["data" + j] = datas[j].name
                            let dd = 0
                            items['data' + j] = 0
                            for (let k = 0; k < datam.length; k++) {
                                if ((datam[k].stringDate === data[i].dates) && (datam[k].name === datas[j].name)) {
                                    items['data' + j] = datam[k].datas
                                    dd = datam[k].totals
                                    items['total'] = dd
                                }
                            }
                        }
                        das.push(items)
                    }
                    das.push(names)
                    console.log('油卡数据查询成功')
                    res.send(das)
                }).catch(err => {
                    console.log(err + '油卡数据查询失败')
                })
            })
        })
    });
    ////////////////////////////修改油卡信息
    app.post('/editCardm', (req, res) => {
        const { stringDate, name, datas, totals, date } = req.body
        cardm.updateOne({ stringDate, name }, {
            $set: {
                datas,
                totals
            }
        }).then(data => {
            if (data.n === 0) {
                cardm.create({
                    createTime: new Date(),
                    name,
                    datas,
                    date,
                    stringDate,
                    totals
                })
            }
            res.send('ok')
        })
    });
    //查询所有大客户有都有如此
    app.get('/findCustomName', (req, res) => {
        member.find({ display: 'YES' }).then(datas => {
            res.send(datas)
        })
    });
    //大客户管理数据查询
    app.get('/custom', (req, res) => {
        custom.find({}).sort({ _id: -1 }).then(data => {
            console.log('大客户管理数据查询成功')
            res.send(data)
        }).catch(err => {
            console.log(err + '大客户管理数据查询失败')
        })
    });
    //查询余额不足10000的客户
    app.get('/customlt', (req, res) => {
        member.find({ display: "YES" }).then(datas => {
            custom.find({}).sort({ _id: -1 }).then(data => {
                let das = data[0].stringDate
                console.log('查询余额不足10000的客户成功')
                let dd = []
                for (let i = 0; i < data.length; i++) {
                    if (data[i].stringDate === das) {
                        if (data[i].totals < 10000) {

                            dd.push(data[i])
                        }
                    }
                }
                res.send(dd)
            }).catch(err => {
                console.log(err + '查询余额不足10000的客户失败')
            });
        }).catch(err => {
            console.log(err + '查询余额不足10000的客户失败')
        })
    });
    //查询某个大客户信息
    app.post('/findCustomList', (req, res) => {
        const { name } = req.body
        custom.find({ name }).sort({ _id: -1 }).then(data => {
            res.send(data)
        })
    });
    //添加大客户信息
    app.post('/addCustom', function(req, res) {
        const {
            name,
            enter,
            out,
            date,
            stringDate
        } = req.body
        custom.find({ name }).sort({ _id: -1 }).limit(1).then(data => {
            const leftover = Number(enter) - Number(out)
            let totals
            if (data.length > 0) {
                totals = data[0].totals + leftover
            } else {
                totals = leftover
            }
            custom.create({
                name,
                enter,
                out,
                date,
                createTime: new Date(),
                leftover,
                totals,
                stringDate
            }, function(err, data) {
                if (!err) {
                    console.log('大客户数据添加成功！')
                    res.send('大客户数据添加成功！')
                } else {
                    console.log('大客户数据添加失败！')
                }
            })
        })
    });
    //查询大客户信息
    app.get('/findCustom', function(req, res) {
        custom.aggregate([{ $group: { _id: "$date", dates: { $max: '$stringDate' }, enters: { $sum: '$enter' }, outs: { $sum: '$out' }, numbers: { $sum: '$totals' } } }]).sort({ _id: -1 }).then(data => {
            res.send(data)
        })
    });
    //查询要编辑的那条大客户信息
    app.post('/findOneCurstom', function(req, res) {
        const { _id } = req.body
        custom.findOne({ _id }).then(data => {
            res.send(data)
        })
    });
    //执行编辑大客户数据
    app.post('/editCustom', (req, res) => {
        const { name, enter, out, _id, date } = req.body
        const leftover = Number(enter) - Number(out)
        custom.updateOne({ _id }, {
            $set: {
                enter,
                out,
                leftover: leftover
            }
        }, function(err, data) {
            if (!err) {
                console.log('执行编辑大客户某天数据成功')
                custom.find({ date: { $lt: date }, name }).sort({ _id: -1 }).limit(1).then(data => {
                    let ts
                    if (data.length > 0) {
                        ts = (data[0].totals + leftover)
                        custom.updateOne({ _id }, {
                            $set: {
                                totals: ts
                            }
                        }, function() {
                            custom.find({ date: { $gt: date }, name }).then(datas => {
                                let tts = ts
                                for (let j = 0; j < datas.length; j++) {
                                    tts = (tts + datas[j].leftover)

                                    custom.updateOne({ _id: datas[j]._id }, {
                                        $set: {
                                            totals: tts
                                        }
                                    }, function() {})
                                }
                            });
                        })
                    } else {
                        ts = leftover
                        custom.updateOne({ _id }, {
                            $set: {
                                totals: ts
                            }
                        }, function() {
                            custom.find({ date: { $gt: date }, name }).then(datas => {

                                let tts = ts
                                for (let j = 0; j < datas.length; j++) {
                                    tts = (tts + datas[j].leftover)

                                    custom.updateOne({ _id: datas[j]._id }, {
                                        $set: {
                                            totals: tts
                                        }
                                    }, function() {})
                                }
                            });
                        })
                    }
                });
                res.send('执行编辑大客户某天数据成功')
            } else {
                console.log(err + '执行编辑大客户某天数据失败')
            }
        })
    });
    //添加数据时，查看要添加的日期是不是已经有了，是不是接天了，数据要第天都录，一天不能漏
    app.post('/checkAdd', (req, res) => {
        const { date, tz } = req.body
        chaiyouData.find({}).sort({ _id: -1 }).limit(1).then(data => {
            if (data.length == 0) {
                const newDate = new Date().getTime()
                const dates = new Date(date).getTime()
                if (newDate > dates) {
                    console.log('符合条件，可以添加')
                    res.send('1')
                } else {
                    console.log('不能选择今天之后的日期哟！')
                    res.send('不能选择今天之后的日期哟！')
                }
            } else {
                const newDate = new Date().getTime() //当前系统时间的时间戳
                const dates = new Date(date).getTime() //上传时间的时间戳
                if (newDate > dates) {
                    const d1 = new Date(data[0].date) //库中最后一条数据的日期
                    const d2 = new Date(date) //用户想要添加的日期
                        //系统当前时间
                    const serd1 = new Date()
                        //系统当前时区
                    const nowTz = (-(serd1.getTimezoneOffset() / 60))
                        //获取库里时间+8小时时区，得到前端页面的时间
                    const timesStorage = (new Date(data[0].date).getTime() - ((nowTz - tz) * 60 * 60 * 1000))
                    const timesStorageDate = new Date(timesStorage)
                    const sendTime = timesStorageDate.getFullYear() + '-' + (timesStorageDate.getMonth() + 1) + '-' + timesStorageDate.getDate()
                        //获取上传时间+8小时时区，得到前端页面时间
                    const timesUpload = (dates - ((nowTz - tz) * 60 * 60 * 1000))
                    const timesUploadDate = new Date(timesUpload)
                    const timesHtml = timesUploadDate.getFullYear() + '-' + (timesUploadDate.getMonth() + 1) + '-' + timesUploadDate.getDate()

                    if (sendTime !== timesHtml) {
                        var dateTime = d1
                            //用数据库中最后一天加1，与想要添加的日期比较，看是不是挨着的两天
                        dateTime = dateTime.setDate(dateTime.getDate() + 1);
                        dateTime = new Date(dateTime);
                        const timesStorageAdd = (dateTime.getTime() - ((nowTz - tz) * 60 * 60 * 1000))
                        const timesStorageDateAdd = new Date(timesStorageAdd)
                        const sendTimeAdd = timesStorageDateAdd.getFullYear() + '-' + (timesStorageDateAdd.getMonth() + 1) + '-' + timesStorageDateAdd.getDate()
                        if (sendTimeAdd === timesHtml) {
                            console.log('符合条件，可以添加')
                            res.send('1')
                        } else {
                            console.log('请按照现有数据日期递增，每天填写数据哟！')
                            res.send('请按照现有数据日期递增，每天填写数据哟！最新数据日期为' + sendTime)
                        }
                    } else {
                        console.log('不能重复填写，每天只能填写一条数据哟！')
                        res.send('不能重复填写，每天只能填写一条数据哟！')
                    }
                } else {
                    console.log('不能选择今天之后的日期哟！')
                    res.send('不能选择今天之后的日期哟！')
                }
            }
        })
    });
    //用户登录验证
    app.post('/login', (req, res) => {
        const { username, password } = req.body
        user.findOne({ username, password }).then(data => {
            if (data) {
                let payload = { username: username, password: password }
                let secret = 'I_LOVE_ME'
                let token = jwt.sign(payload, secret)
                res.send({
                    code: '200',
                    msg: "登录成功",
                    token: token,
                    role: data.role,
                    name: data.username
                })
            } else {
                res.send('100')
            }
        }).catch(err => {})
    });
    //添加用户
    app.post('/addUser', (req, res) => {
        const { username, password, email, tel } = req.body
        user.findOne({ username }).then(data => {
            if (data) {
                res.send('用户名已存在')
            } else {
                user.create({
                    username,
                    password,
                    email,
                    tel,
                })
                res.send('添加成功')
            }
        })
    });
    //查询所有用户信息
    app.get('/findUser', (req, res) => {
        if (req.query.role === '超级用户') {
            user.find({ display: "YES" }).then(data => {
                res.send(data)
            })
        } else {
            user.find({ role: req.query.role, display: "YES" }).then(data => {
                res.send(data)
            })
        }
    });
    //编辑前先查询
    app.post('/findOneUser', (req, res) => {
        const { _id } = req.body
        user.findOne({ _id }).then(data => {
            res.send(data)
        })
    });
    //执行编辑
    app.post('/updateUser', (req, res) => {
        const { _id, username, password, email, tel } = req.body
        user.updateOne({ _id }, {
            $set: {
                username,
                password,
                email,
                tel
            }
        }, function() {
            res.send('编辑用户成功')
        })
    });
    //删除用户
    app.post('/deleteUser', (req, res) => {
        const { _id } = req.body
            // user.deleteMany({ _id }, function(err, data) {
            //     if (!err) res.send(data)
            //     else console.log(err, '删除用户失败！')
            // })
        user.updateOne({ _id }, {
            $set: {
                display: "NO"
            }
        }, function() {
            res.send('删除用户成功')
        })
    });
    //添加会员
    app.post('/addMember', (req, res) => {
        const { name, alias } = req.body
        member.findOne({ name }).then(data => {
            if (data) {
                res.send('该会员已存在')
            } else {
                member.create({
                    name,
                    alias
                })
                res.send('添加会员成功')
            }
        })
    });
    //查询所有会员信息
    app.get('/findMember', (req, res) => {
        member.find({ display: "YES" }).then(data => {
            res.send(data)
        });
    });
    //编辑前先查询
    app.post('/findOneMember', (req, res) => {
        const { _id } = req.body
        member.findOne({ _id }).then(data => {
            res.send(data)
        })
    });
    //执行编辑会员
    app.post('/updateMember', (req, res) => {
        const { _id, name } = req.body
        member.updateOne({ _id }, {
            $set: {
                name
            }
        }, function() {
            res.send('编辑用户成功')
        })
    });
    //删除会员
    app.post('/deleteMember', (req, res) => {
        const { _id } = req.body
        member.updateOne({ _id }, {
            $set: {
                display: "NO"
            }
        }, function() {
            res.send('删除会员成功')
        })
    });
    //添加散户
    app.post('/addSanhu', (req, res) => {
        const { name, alias } = req.body
        sanhu.findOne({ name }).then(data => {
            if (data) {
                res.send('该散户已存在')
            } else {
                sanhu.create({
                    name,
                    alias
                })
                res.send('添加散户成功')
            }
        })
    });
    //查询所有会员信息
    app.get('/findSanhu', (req, res) => {
        sanhu.find({ display: "YES" }).then(data => {
            res.send(data)
        });
    });
    //编辑前先查询
    app.post('/findOneSanhu', (req, res) => {
        const { _id } = req.body
        sanhu.findOne({ _id }).then(data => {
            res.send(data)
        })
    });
    //执行编辑会员
    app.post('/updateSanhu', (req, res) => {
        const { _id, name } = req.body
        sanhu.updateOne({ _id }, {
            $set: {
                name
            }
        }, function() {
            res.send('编辑散户成功')
        })
    });
    //删除会员
    app.post('/deleteSanhu', (req, res) => {
        const { _id } = req.body
        sanhu.updateOne({ _id }, {
            $set: {
                display: "NO"
            }
        }, function() {
            res.send('删除散户成功')
        })
    });
    //添加油卡管理
    app.post('/addCardsMan', (req, res) => {
        const { name, alias } = req.body
        cardsMan.findOne({ name }).then(data => {
            if (data) {
                res.send('该油卡存在')
            } else {
                cardsMan.create({
                    name,
                    alias
                })
                res.send('添加油卡类型成功')
            }
        })
    });
    //查询所有会员信息
    app.get('/findCardsMan', (req, res) => {
        cardsMan.find({ display: "YES" }).then(data => {
            res.send(data)
        });
    });
    //编辑前先查询
    app.post('/findOneCardsMan', (req, res) => {
        const { _id } = req.body
        cardsMan.findOne({ _id }).then(data => {
            res.send(data)
        })
    });
    //执行编辑会员
    app.post('/updateCardsMan', (req, res) => {
        const { _id, name } = req.body
        cardsMan.updateOne({ _id }, {
            $set: {
                name
            }
        }, function() {
            res.send('编辑油卡类型成功')
        })
    });
    //删除会员
    app.post('/deleteCardsMan', (req, res) => {
        const { _id } = req.body
        cardsMan.updateOne({ _id }, {
            $set: {
                display: "NO"
            }
        }, function() {
            res.send('删除油卡类型成功')
        })
    });
    //添加柴油类型管理
    app.post('/addChaiyou', (req, res) => {
        const { name, alias } = req.body
        chaiyou.findOne({ name }).then(data => {
            if (data) {
                res.send('该柴油类型存在')
            } else {
                chaiyou.create({
                    name,
                    alias
                })
                res.send('添加柴油类型成功')
            }
        })
    });
    //查询所有会员信息
    app.get('/findChaiyou', (req, res) => {
        chaiyou.find({ display: "YES" }).then(data => {
            res.send(data)
        });
    });
    //编辑前先查询
    app.post('/findOneChaiyou', (req, res) => {
        const { _id } = req.body
        chaiyou.findOne({ _id }).then(data => {
            res.send(data)
        })
    });
    //执行编辑会员
    app.post('/updateChaiyou', (req, res) => {
        const { _id, name } = req.body
        chaiyou.updateOne({ _id }, {
            $set: {
                name
            }
        }, function() {
            res.send('编辑柴油类型成功')
        })
    });
    //删除会员
    app.post('/deleteChaiyou', (req, res) => {
        const { _id } = req.body
        chaiyou.updateOne({ _id }, {
            $set: {
                display: "NO"
            }
        }, function() {
            res.send('删除柴油类型成功')
        })
    });
    //添加尿素类型管理
    app.post('/addNiaosu', (req, res) => {
        const { name, alias } = req.body
        niaosu.findOne({ name }).then(data => {
            if (data) {
                res.send('该油卡存在')
            } else {
                niaosu.create({
                    name,
                    alias
                })
                res.send('添加油卡类型成功')
            }
        })
    });
    //查询所有会员信息
    app.get('/findNiaosu', (req, res) => {
        niaosu.find({ display: "YES" }).then(data => {
            res.send(data)
        });
    });
    //编辑前先查询
    app.post('/findOneNiaosu', (req, res) => {
        const { _id } = req.body
        niaosu.findOne({ _id }).then(data => {
            res.send(data)
        })
    });
    //执行编辑会员
    app.post('/updateNiaosu', (req, res) => {
        const { _id, name } = req.body
        niaosu.updateOne({ _id }, {
            $set: {
                name
            }
        }, function() {
            res.send('编辑油卡类型成功')
        })
    });
    //删除会员
    app.post('/deleteNiaosu', (req, res) => {
        const { _id } = req.body
        niaosu.updateOne({ _id }, {
            $set: {
                display: "NO"
            }
        }, function() {
            res.send('删除油卡类型成功')
        })
    });
    // 各会员消费情况饼图 //////////////////
    app.get("/reportShouruData", (req, res) => {
        const { tz, das } = req.query
        member.find({ display: "YES" }).then(names => {
            custom.aggregate([{ $group: { _id: "$date", dates: { $max: '$stringDate' } } }]).sort({ _id: -1 }).limit(Number(das)).then(datedata => {
                custom.find({}).sort({ _id: -1 }).then(data => {
                    let newData = []
                    let newName = []
                    for (let i = 0; i < names.length; i++) {
                        let dd1 = {
                            value: 0,
                            name: names[i].name
                        }
                        newData.push(dd1)
                        newName[i] = names[i].name
                    }
                    for (let i = 0; i < data.length; i++) {
                        for (let j = 0; j < datedata.length; j++) {
                            if (datedata[j].dates === data[i].stringDate) {
                                for (let item in newData) {
                                    if (newData[item].name === data[i].name) {
                                        newData[item].value += data[i].out
                                    }
                                }
                            }
                        }
                    }
                    console.log('各会员消费情况饼图')
                    datas = {
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        legend: {
                            top: '5%',
                            left: 'center'
                        },
                        series: [{
                            name: '会员名称',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            avoidLabelOverlap: false,
                            label: {
                                show: false,
                                position: 'center'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: '20',
                                    fontWeight: 'bold'
                                }
                            },
                            labelLine: {
                                show: false
                            },
                            data: newData
                        }]
                    }
                    res.send(datas)
                }).catch(err => {
                    console.log(err + '收入表格报表数据查询失败')
                })
            })
        })
    });
    //尿素的进出货报表  //////////////////////销售情况报表  完成
    app.get('/reportUrealData', (req, res) => {
        let dd1
        const { tz, das } = req.query
        niaosu.find({ display: 'YES' }).then(niaosu => {
            chaiyou.find({ display: 'YES' }).then(chaiyou => {
                urea1.aggregate([{ $group: { _id: "$date", numbers: { $sum: '$out' }, dates: { $max: '$stringDate' } } }]).sort({ _id: -1 }).limit(Number(das)).then(data1 => {
                    dd1 = data1
                }).then(() => {
                    chaiyouShouyi.aggregate([{ $group: { _id: "$date", numbers: { $sum: '$datas' }, dates: { $max: '$stringDate' } } }]).sort({ _id: -1 }).limit(Number(das)).then(data2 => {
                        //系统当前时间
                        const serd1 = new Date()
                            //系统当前时区
                        const nowTz = (-(serd1.getTimezoneOffset() / 60))
                        let dataUrea1 = []
                        let dataUrea2 = []
                        let dataDate = []
                        for (let i = 0; i < data2.length; i++) {
                            if (dd1[i].numbers) {
                                dataUrea1[i] = dd1[i].numbers
                            } else {
                                dataUrea1[i] = 0
                            }
                            if (data2[i].numbers) {
                                dataUrea2[i] = data2[i].numbers
                            } else {
                                dataUrea2[i] = 0
                            }
                            const days = dd1[i].dates.split('-')
                            dataDate[i] = days[1] + '-' + days[2]
                        }
                        datas = {
                            title: {
                                // text: '两类油的销量情况',
                            },
                            textStyle: {
                                // color: '#ffffff'
                            },
                            tooltip: {
                                trigger: 'axis',

                            },
                            legend: {
                                // data: ['第一号油', '第二号油', '总额'],
                                data: ['柴油', '尿素'],
                                textStyle: {
                                    // color: '#fff'
                                }
                            },
                            grid: {
                                left: '1%',
                                right: '1%',
                                bottom: '3%',
                                containLabel: true
                            },
                            toolbox: {
                                show: false,
                                // show: true,
                                feature: {
                                    dataZoom: {
                                        yAxisIndex: 'none'
                                    },
                                    dataView: { readOnly: false },
                                    magicType: { type: ['line', 'bar'] },
                                    restore: {},
                                    saveAsImage: {}
                                }
                            },
                            // color: ["red", "#C605F0", '#DB8E8E'],
                            xAxis: {
                                type: 'category',
                                boundaryGap: false,
                                data: dataDate
                            },
                            yAxis: {
                                type: 'value',
                                // name: '单位（升）',
                                axisLabel: {
                                    formatter: '{value}'
                                }
                            },
                            series: [{
                                    name: '柴油',
                                    type: 'line',
                                    data: dataUrea2
                                },
                                {
                                    type: 'line',
                                    name: '尿素',
                                    data: dataUrea1,
                                }
                            ]
                        }
                        res.send(datas)
                    })
                })
            })
        })
    });
    //各油卡消费情况饼图
    app.get("/reportCardData", (req, res) => {
        const { tz, das } = req.query
        cardsMan.find({ display: "YES" }).then(cardName => {
            cardm.aggregate([{ $group: { _id: "$date", dates: { $max: '$stringDate' } } }]).sort({ _id: -1 }).limit(Number(das)).then(cardDate => {
                cardm.find({}).sort({ _id: -1 }).then(data => {
                    //系统当前时间
                    const serd1 = new Date()
                        //系统当前时区
                    const nowTz = (-(serd1.getTimezoneOffset() / 60))
                    console.log('油卡表格数据查询成功')
                    let newData = []
                    let newName = []
                    for (let i = 0; i < cardName.length; i++) {
                        let dd1 = {
                            value: 0,
                            name: cardName[i].name
                        }
                        newData.push(dd1)
                        newName[i] = cardName[i].name
                    }
                    for (let i = 0; i < data.length; i++) {
                        for (let j = 0; j < cardDate.length; j++) {
                            if (cardDate[j].dates === data[i].stringDate) {
                                for (let item in newData) {
                                    if (newData[item].name === data[i].name) {
                                        newData[item].value += data[i].datas
                                    }
                                }
                            }
                        }
                    }
                    // let dd1 = { value: 0, name: '万能' }
                    // let dd2 = { value: 0, name: '汇惠' }
                    // let dd3 = { value: 0, name: '吕昌' }
                    // let dd4 = { value: 0, name: '中天' }
                    // let dd5 = { value: 0, name: '国卡' }
                    // let dateData = ['product']
                    // for (let i = 0; i < data.length; i++) {
                    //     dd1.value += data[i].wanneng
                    //     dd2.value += data[i].huihui
                    //     dd3.value += data[i].lvchang
                    //     dd4.value += data[i].zhongtian
                    //     dd5.value += data[i].guoka
                    //     let days = data[i].stringDate
                    //     dateData[i + 1] = days[1] + '-' + days[2]
                    // }
                    option = {
                        legend: {
                            textStyle: {
                                color: ''
                            },
                            bottom: 10,
                            left: 'center',
                            // data: ['万能', '汇惠', '吕昌', '中天', '国卡']
                            data: newName
                        },
                        textStyle: {
                            color: ''
                        },
                        title: {
                            // text: '油卡使用情况'
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        series: [{
                            name: '油卡类型',
                            type: 'pie',
                            id: 'pie',
                            radius: '65%',
                            center: ['50%', '50%'],
                            emphasis: { focus: 'data' },
                            selectedMode: 'single',
                            label: {
                                // formatter: '{b}: {@2012} ({d}%)'
                            },
                            // encode: {
                            //     itemName: 'product',
                            //     value: dateData[1],
                            //     tooltip: dateData[1]
                            // }
                            // data: [dd1, dd2, dd3, dd4, dd5],
                            data: newData,
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }]
                    };
                    res.send(option)
                }).catch(err => {
                    console.log(err + '收入表格数据查询失败')
                })
            })
        })
    });
    //收入情况(客户，散户，油卡)报表  /////////////(收入情况折线图) 完成
    app.get('/reportCustomData', function(req, res) {
        const { tz, das } = req.query
        custom.aggregate([{ $group: { _id: "$date", numbers: { $sum: '$out' } } }]).sort({ _id: -1 }).limit(Number(das)).then(data => {
            sanhuData.aggregate([{ $group: { _id: "$date", numbers: { $sum: '$datas' } } }]).sort({ _id: -1 }).limit(Number(das)).then(data2 => {
                cardm.aggregate([{ $group: { _id: "$date", numbers: { $sum: '$datas' }, dates: { $max: '$stringDate' } } }]).sort({ _id: -1 }).limit(Number(das)).then(data3 => {
                    //系统当前时间
                    const serd1 = new Date()
                        //系统当前时区
                    const nowTz = (-(serd1.getTimezoneOffset() / 60))

                    let dateData = []
                    let customData = []
                    let shouruData = []
                    let cardsData = []
                    let sanhuPoint = []
                    let customPoint = []
                    let cardPoint = []
                    for (let i = 0; i < data2.length; i++) {

                        // let timesStorage = (new Date(data[i]._id).getTime() - ((nowTz - tz) * 60 * 60 * 1000))
                        // let timesStorageDate = new Date(timesStorage)
                        // let days = (timesStorageDate.getMonth() + 1) + '-' + timesStorageDate.getDate()
                        let days = data3[i].dates.split('-')
                            // let das = (data[i]._id.getMonth() + 1) + '月' + data[i]._id.getDate() + "日"
                        dateData[i] = days[1] + '-' + days[2]
                        customData[i] = data[i].numbers
                        shouruData[i] = data2[i].numbers
                        cardsData[i] = data3[i].numbers
                        let p1 = {}
                        p1.name = '散户'
                        p1.value = data2[i].numbers
                        p1.xAxis = i
                        p1.yAxis = data2[i].numbers
                        sanhuPoint[i] = p1
                        let p2 = {}
                        p2.name = '客户'
                        p2.value = data[i].numbers
                        p2.xAxis = i
                        p2.yAxis = data[i].numbers
                        customPoint[i] = p2
                        let p3 = {}
                        p3.name = '油卡'
                        p3.value = data3[i].numbers
                        p3.xAxis = i
                        p3.yAxis = data3[i].numbers
                        cardPoint[i] = p3

                    }


                    datas = {
                        title: {
                            // text: '两类油的销量情况',
                        },
                        textStyle: {
                            // color: '#ffffff'
                        },
                        tooltip: {
                            trigger: 'axis',

                        },
                        legend: {
                            // data: ['第一号油', '第二号油', '总额'],
                            data: ['散户', '油卡', '会员'],
                            textStyle: {
                                // color: '#fff'
                            }
                        },
                        grid: {
                            left: '1%',
                            right: '1%',
                            bottom: '3%',
                            width: '98%',
                            height: '100%',
                            containLabel: true
                        },
                        toolbox: {
                            show: false,
                            // show: true,
                            feature: {
                                dataZoom: {
                                    yAxisIndex: 'none'
                                },
                                dataView: { readOnly: false },
                                magicType: { type: ['line', 'bar'] },
                                restore: {},
                                saveAsImage: {}
                            }
                        },























                        // color: ["red", "#C605F0", '#DB8E8E'],
                        // color: ["red", "#390F0F"],
                        xAxis: {
                            type: 'category',
                            boundaryGap: false,
                            data: dateData
                        },
                        yAxis: {
                            type: 'value',
                            // name: '单位（升）',
                            axisLabel: {
                                formatter: '{value}'
                            }
                        },
                        series: [{
                                name: '散户',
                                type: 'line',
                                data: shouruData,
                                // markPoint: {
                                //     data: sanhuPoint
                                // }

                            },
                            {
                                type: 'line',
                                name: '油卡',
                                data: cardsData,
                                // markPoint: {
                                //     data: cardPoint
                                // }
                            },
                            {
                                type: 'line',
                                name: '会员',
                                data: customData,
                                // markPoint: {
                                //     data: customPoint
                                // }

                            }
                        ]
                    }
                    res.send(datas)
                })
            })
        })
    });
}, (err) => {
    console.log('数据库连接失败', err)
})